<template>
  <Transition>

      <PopMenu ref="menuRef" @hide="hide" v-show="isVisible" :items="items" id="globalMenu" :style="{
        left: `${menuX}px`,
        top: `${menuY}px`,
      }" />

  </Transition>
  <slot></slot>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, provide, ref, shallowRef, useTemplateRef, VNodeRef, nextTick } from 'vue';
import PopMenu from './pop-menu.vue';
import type { MenuItem } from './pop-menu.vue';
import { IPopMenuHookReturn, PopMenuSymbol } from './usePopMenu';

const items = shallowRef<MenuItem[]>([]);
const menuX = ref(0);
const menuY = ref(0);
const isVisible = ref(false);
const menuRef = ref(null);

async function show(menuItems: MenuItem[], x: number, y: number) {
  isVisible.value = true;
  items.value = menuItems;
  menuX.value = x;
  menuY.value = y;
  await nextTick();
  // 避免超出屏幕
  const menuElement = menuRef.value?.$el;
  if (menuElement) {
    const menuHeight = menuElement.offsetHeight;
    const windowHeight = window.innerHeight;
    if (y + menuHeight > windowHeight) {
      const excess = y + menuHeight - windowHeight;
      menuY.value = y - excess;
    }
  }
}

function hide() {
  console.log('pop menu hide');
  isVisible.value = false;
}

function toggle(menuItems: MenuItem[], x: number, y: number) {
  if (isVisible.value) {
    hide();
  } else {
    show(menuItems, x, y);
  }
}

const provideData: IPopMenuHookReturn = {
  show,
  hide,
  toggle
};
provide(PopMenuSymbol, provideData);
</script>

<style lang="scss">
#globalMenu {
  position: absolute;
  z-index: 1;
}

.v-enter-active,
.v-leave-active {
  transition: opacity 0.1s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}
</style>